package com.jf3q.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.domain.EduOrder;
import com.jf3q.common.mapper.EduOrderMapper;
import com.jf3q.common.utils.OrderNoUtil;
import com.jf3q.common.vo.CourseWebVo;
import com.jf3q.front.service.CourseService;
import com.jf3q.front.service.MemberService;
import com.jf3q.front.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class OrderServiceImpl extends ServiceImpl<EduOrderMapper, EduOrder> implements OrderService {
    @Autowired
    private MemberService memberService;
    @Autowired
    private CourseService courseService;
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public EduOrder hasOrderCourse(String courseId, String memberId) {
        LambdaQueryWrapper<EduOrder> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(EduOrder::getCourseId, courseId);
        queryWrapper.eq(EduOrder::getMemberId, memberId);
        return  this.getOne(queryWrapper);

    }



    @Override
    public String createOrders(String courseId, String memberId) {
        EduOrder eduOrder = hasOrderCourse(courseId, memberId);

        if(eduOrder!=null && eduOrder.getStatus()==0 ){

            //已经下单但未支付，这种情况直接去支付（不要再生产订单了）

            return eduOrder.getOrderNo();

        }
        if(eduOrder!=null && eduOrder.getStatus()==1 ){
            if (eduOrder.getPayType()==0) {
                //说明是免费课程
                throw new RuntimeException("您已经报名了该课程，请直接在大纲里看视频即可");
            }else{
                throw new RuntimeException("您已经购买过该课程，请勿重复购买");
            }
        }
        //根据用户id获取用户信息
        EduMember member = memberService.getById(memberId);

        //根据课程id获取课信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);


        //创建Order对象，向order对象里面设置需要数据
        EduOrder order = new EduOrder();
        order.setOrderNo(OrderNoUtil.getOrderNo());//订单号
        order.setCourseId(courseId); //课程id
        order.setCourseTitle(courseWebVo.getTitle());
        order.setCourseCover(courseWebVo.getCover());
        order.setTeacherName(courseWebVo.getTeacherName());
        order.setTeacherId(courseWebVo.getTeacherId());
        order.setTotalFee(courseWebVo.getPrice());
        order.setMemberId(memberId);
        order.setMobile(member.getMobile());
        order.setNickname(member.getNickname());

        if(courseWebVo.getPrice().compareTo(BigDecimal.valueOf(0))==0 ){
            order.setStatus(Byte.valueOf("1"));  //订单状态（0：未支付 1：已支付）
            order.setPayType(Byte.valueOf("0"));//支付类型（0：免费课程，1：微信 2：支付宝）

            //修改课程的购买数
            Long buyCount = redisTemplate.opsForHash().increment("course_" + order.getCourseId(), "buyCount", 1);
            //修改老师的排行
            redisTemplate.opsForZSet().incrementScore("teacherBuyCount",order.getTeacherId(),1);//原有次数+1（每次购买都算加一次）

        }else{
            order.setStatus(Byte.valueOf("0"));
            //暂时只接了支付宝支付，所以这里设置2
            order.setPayType(Byte.valueOf("2"));//支付类型（0：免费课程，1：微信 2：支付宝）
        }

        baseMapper.insert(order);
        //返回订单号
        return order.getOrderNo();

    }
}
